<?php
declare (strict_types=1);

namespace app\services\public;

use app\services\BaseServices;
use app\dao\public\SmsRecordDao;
use crmeb\exceptions\AdminException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

/**
 *
 * Class SendCodeServices
 * @package app\services\public
 * @mixin SmsRecordDao
 */
class SendCodeServices extends BaseServices
{

    /**
     * SendCodeServices constructor.
     * @param SmsRecordDao $dao
     */
    public function __construct(SmsRecordDao $dao)
    {
        $this->dao = $dao;
    }


    /**
     * 发送短信验证码
     * @param string $mobile
     * @return array
     */
    public function send(string $mobile): array
    {
        # 阿里云短信测试
//        $mobile = "15050640606";
//        $template = "SMS_154950909";

//        if ($mobile == '15050640606' || $mobile == '13814615546') {
//            $code = 1111;
//            cache('tel' . $mobile, $code, 1200);
//            return [
//                "RequestId" => "10B5AB40-420F-5507-990E-768BCA3B9EB4",
//                "Message" => "OK",
//                "BizId" => "975209764204994356^0",
//                "Code" => "OK"
//            ];
//        }

        if ($mobile != '17138009808' && $mobile != '17138009271' && $mobile != '17190011705') {
            $head_3 = substr($mobile, 0, 3);
            if ($head_3 == 162 || $head_3 == 165 || $head_3 == 171 || $head_3 == 167) {
                throw new AdminException('检测出你是机刷号码，暂无法提供短信验证码服务！');
            }
        }

        $head_4 = substr($mobile, 0, 4);
        if ($head_4 == 1700 || $head_4 == 1701 || $head_4 == 1702 || $head_4 == 1703 || $head_4 == 1704 || $head_4 == 1705 || $head_4 == 1706 || $head_4 == 1707 || $head_4 == 1708 || $head_4 == 1709) {
            throw new AdminException('检测出你是机刷号码，暂无法提供短信验证码服务！');
        }

        $code = cmf_get_verification_code($mobile);

        $result = send_verification_code($mobile, $code);

        if ($result['Code'] == 'OK') {
            //存到缓存当中,并且返回json数据给前端
            cache('tel' . $mobile, $code, 600);
            return $result;
        } else {
            switch ($result['Code']) {
                case 'isv.BUSINESS_LIMIT_CONTROL':
                    if (strpos($result['Message'], '小时') !== false) {
                        // 包含
                        throw new AdminException('一小时内只能发送5次，请稍后再试');
                    }
                    if (strpos($result['Message'], '天级流控') !== false) {
                        // 包含
                        throw new AdminException('一天内最多只能发送20次');
                    }
                    throw new AdminException('一分钟内只能发送1次，请稍后再试');
                case 'isv.DAY_LIMIT_CONTROL':
                    throw new AdminException('今日发送短信次数已达上限');
                default:
                    throw new AdminException($result['Message']);
            }
        }


    }
}
